package com.seamtop.cuber.core;

import com.seamtop.cuber.common.entriy.TransData;
import io.searchbox.client.JestClient;
import io.searchbox.client.JestResult;
import io.searchbox.core.Bulk;
import io.searchbox.core.Index;
import io.searchbox.indices.CreateIndex;
import io.searchbox.indices.IndicesExists;

import java.util.HashMap;
import java.util.List;

/**
 * Created by zongjunfeng on 2015/9/21.
 */
public class ESUtil {

    public static void index(JestClient jestClient,List<TransData> transDataList) throws Exception{
        if(transDataList == null || transDataList.size() == 0){
            return ;
        }

        HashMap<String,String> esMap = new HashMap<String,String>();
        for(int i=0;i<transDataList.size();i++){
            TransData transData = transDataList.get(i);
            String id = transData.getRowKey();
            String [] idArray = id.split("\\|");
            String factName = idArray[0].split("_")[0];
            String period = idArray[0].split("_")[1];
            if(transData.getFactType() == 0 || transData.getFactType() == 1){
                esMap.put("reducer",factName);
            }else if(transData.getFactType() == 2){
                esMap.put("counter",factName);
            }
            esMap.put("period",period);
            if(idArray.length == 2){
                String [] paramsArray = idArray[1].split("_");
                if(paramsArray != null){
                    for(int j=0;j<paramsArray.length;j++){
                        String [] tempArray = paramsArray[j].split(":");
                        esMap.put(tempArray[0],tempArray[1]);
                    }
                }
            }
            esMap.put("value",transData.getValue());
            IndicesExists indicesExists = new IndicesExists.Builder("cuber").build();
            JestResult result = jestClient.execute(indicesExists);
            if (!result.isSucceeded()) {
                CreateIndex createIndex = new CreateIndex.Builder("cuber").build();
                jestClient.execute(createIndex);
            }

            Bulk bulk = new Bulk.Builder()
                    .addAction(new Index.Builder(esMap).index("cuber").type(factName).id(id).build())
                    .build();
            jestClient.execute(bulk);
        }
    }

}
